const { poolQuery } = require("../utils/db");
const moment = require("moment");
const areaModel = require("../models/areaModel");
const areaService = {
  checkId(req) {
    return new Promise((resolve, reject) => {
      const { id } = req.params;
      if (id) {
        poolQuery(areaModel.checkAreaId, id, (err, rows) => {
          if (err) return reject(err);
          if (rows.length > 0) return resolve(true);
          reject("数据不存在");
        });
      } else {
        reject("id不能为空");
      }
    });
  },
  async addArea(req, res) {
    const params = {
      ...req.body,
      create_time: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
    poolQuery(areaModel.addAreaSql, params, (err, rows) => {
      if (err) return res.tip(err);
      if (rows.affectedRows !== 1) return res.tip("区域添加失败");
      return res.tip("区域添加成功", 0);
    });
  },
  async editArea(req, res) {
    const params = {
      ...req.body,
      update_time: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
    poolQuery(areaModel.editAreaSql, [params, params.id], (err, rows) => {
      if (err) return res.tip(err);
      if (rows.affectedRows !== 1) return res.tip("区域修改失败");
      return res.tip("区域修改成功", 0);
    });
  },
  async deleteArea(req, res) {
    poolQuery(areaModel.getAll, async (err, rows) => {
      if (err) return res.tip(err);
      if (rows.length > 0) {
        const { id } = req.params;
        const allSubIdList = getAllSubId(id, rows);
        poolQuery(areaModel.deleteSql, [allSubIdList], (err, rows) => {
          if (err) return res.tip(err);
          if (rows.affectedRows === 0) return res.tip("区域删除失败");
          return res.tip("区域删除成功", 0);
        });
      }
    });
  },
};
function getAllSubId(id, rows, idList = []) {
  idList.push(id);
  const filterList = rows.filter((item) => item.parentId === id);
  if (filterList.length > 0) {
    filterList.forEach((item) => {
      idList = getAllSubId(item.id, rows, idList);
    });
  }
  return idList;
}

module.exports = areaService;
